import 'dart:core';

import 'package:flutter/material.dart';
import 'package:flutter_bsbdj/bean/mei_tui.dart';
import 'package:dio/dio.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_bsbdj/data_base/image_table.dart';
import 'package:flutter_bsbdj/dialogs/big_image_dialog.dart';
import 'package:flutter_bsbdj/dialogs/down_load_pormat.dart';
import 'package:flutter_bsbdj/utils/shared_preferences_util.dart';

class MeiTuPager extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MtWidget();
  }
}

class MtWidget extends State<MeiTuPager> {
  String UI_MODEL="list_grid";
  int page = 1;
  List<MeituItem> _images;
  ScrollController _scrollController = ScrollController();
  bool _listOrGrid = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController.addListener(() {
      var p = _scrollController.position.pixels;
      var m = _scrollController.position.maxScrollExtent;
      if (p == m) {
        page++;
        _getMeiTu();
      }
    });
    _getDataForDatabase();

    SharedPrefrenceUtil.getBoolValue(UI_MODEL, _listOrGrid).then((model){
      if(_listOrGrid!=model) {
        setState(() {
          _listOrGrid = model;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("美图"),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              _listOrGrid ? Icons.list : Icons.apps,
              color: Colors.white,
            ),
            onPressed: () {
              setState(() {
                _listOrGrid = !_listOrGrid;
                SharedPrefrenceUtil.setBoolValue(UI_MODEL, _listOrGrid);
              });
            },
          )
        ],
      ),
      body: Container(
        child: _listOrGrid
            ? GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3,
                    childAspectRatio: 1.0,
                    crossAxisSpacing: 10,
                    mainAxisSpacing: 10),
                itemCount: _images == null ? 0 : _images.length,
                itemBuilder: (content, index) {
                  return _imageItem(_images[index]);
                },
                controller: _scrollController,
              )
            : ListView.builder(
                itemCount: _images == null ? 0 : _images.length + 1,
                itemBuilder: (content, index) {
                  if (index == _images.length) {
                    return Center(
                      child: Container(
                        width: 30,
                        height: 30,
                        margin: EdgeInsets.all(5),
                        child: CircularProgressIndicator(),
                      ),
                    );
                  } else {
                    return _imageItem(_images[index]);
                  }
                },
                controller: _scrollController,
              ),
      ),
    );
  }

  Widget _imageItem(MeituItem item) {
    return Container(
      color: Colors.white70,
      padding: EdgeInsets.all(5),
      child: _cachedImage(item.url, () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => ShowBigImage(item.url, false)));
//        showDialog(
//            context: context,
//            builder: (BuildContext context){
//              return BigImageDialog(item.url);
//            });
      }),
    );
  }

  void _getMeiTu() async {
    var t = await Dio()
        .get("http://gank.io/api/data/%E7%A6%8F%E5%88%A9/15/$page")
        .then((result) {
      try {
        Meitu meiTu = Meitu.fromJson(result.data);
        print(meiTu);
        if(meiTu.results!=null && meiTu.results.length>0) {
          var d = _images;
          if (page == 1) {
            d = meiTu.results;
          } else {
            d.addAll(meiTu.results);
          }
          //只有当前widget还在 tree中才设置值
          if (mounted) {
            setState(() {
              _images = d;
            });
          }
          ImageTable.getInstance().insertList(meiTu.results);
        }
      } on DioError catch (e) {}
    }).catchError((e) {
      print(e);
    });
  }

  void _getDataForDatabase() async{
    await ImageTable.getInstance().getAllInfo().then((data){
      if(data!=null&& data.length>0){
        setState(() {
          _images=data;
        });
      }else{
        print("*******");
        _getMeiTu();
      }

    }).catchError((e){
      print("--------");
      print(e.toString());
      _getMeiTu();
    });
  }

  //返回带错误提示的image
  Widget _cachedImage(String url, Function function) {
    return GestureDetector(
      child: CachedNetworkImage(
        imageUrl: url,
        placeholder: (context, str) => Image.asset("images/ic_loading.gif"),
        errorWidget: (context, str, object) => Image.asset("images/error.png"),
      ),
      onTap: function,
      onLongPress: () {
        showDialog(
            context: context,
            builder: (BuildContext context) {
              return DownLoadPrompt(url);
            });
      },
    );
  }
}
